//
//  LXCarHomeViewController.m
//  INMOTION_CustomMadeProject
//
//  Created by cjg on 2021/3/22.
//  Copyright © 2021 cjg. All rights reserved.
//

#import "LXCarHomeViewController.h"
#import "IMTConfig.h"
#import "LXCarSettingViewController.h"
#import "LXSearchCarView.h"
#import "IMTCANManager.h"
#import "IMTCarManager.h"
#import "NSObject+HUD.h"
#import "KSLanguageManager.h"
#import "KSBLEManager.h"
#import "IMTUnitHelper.h"
#import "LXActivationViewController.h"
#import "LXSearchViewController.h"
#import "LXCustom.h"
#import "IMTHTTPSessionManager.h"
#import "LXFirmwareModel.h"
#import "NewFirmwareUpdateViewController.h"
#import "AppTypeTool.h"
#import "UIImage+Category.h"
#import "BleNameCheck.h"


@interface LXCarHomeViewController ()<UIScrollViewDelegate, LXSearchCarViewDelegate>

// 数据界面
@property (weak, nonatomic) IBOutlet UILabel *maxSpeedValueLB;
@property (weak, nonatomic) IBOutlet UILabel *maxSpeedUintLB;
@property (weak, nonatomic) IBOutlet UILabel *maxSpeedTitleLB;
@property (weak, nonatomic) IBOutlet UILabel *averageSpeedLB;
@property (weak, nonatomic) IBOutlet UILabel *averageSpeedUintLB;
@property (weak, nonatomic) IBOutlet UILabel *averageSpeedTitleLB;
@property (weak, nonatomic) IBOutlet UILabel *thisTimeValueLB;
@property (weak, nonatomic) IBOutlet UILabel *thisTimeUintLB;
@property (weak, nonatomic) IBOutlet UILabel *thisTimeTitleLB;
@property (weak, nonatomic) IBOutlet UILabel *thisMileValueLB;
@property (weak, nonatomic) IBOutlet UILabel *thisMileUnitLB;
@property (weak, nonatomic) IBOutlet UILabel *thisMileTitleLB;
@property (weak, nonatomic) IBOutlet UILabel *temperatureValueLB;
@property (weak, nonatomic) IBOutlet UILabel *temperaturUnitLB;
@property (weak, nonatomic) IBOutlet UILabel *temperatureTitleLB;
@property (weak, nonatomic) IBOutlet UILabel *toalMileValueLB;
@property (weak, nonatomic) IBOutlet UILabel *toalMileUnitLB;
@property (weak, nonatomic) IBOutlet UILabel *toalMileTitleLB;

@property (weak, nonatomic) IBOutlet UILabel *powerOnTimeValueLB;
@property (weak, nonatomic) IBOutlet UILabel *powerOnTimeUnitLB;
@property (weak, nonatomic) IBOutlet UILabel *powerOnTimeTitleLB;

@property (weak, nonatomic) IBOutlet UILabel *bottomBatteryValueLB;
@property (weak, nonatomic) IBOutlet UILabel *bottomBatteryTitleLB;



@property (nonatomic , strong)LXSearchCarView *searchView;
@property (nonatomic , strong)CarModel *carModel;
@property (nonatomic , strong)NSTimer *timer;
@property (nonatomic , assign)CGFloat count;
@property (nonatomic , assign)CGFloat lastAngle;
@property (nonatomic , assign)CGFloat desAngle;
@property (nonatomic , strong)CAShapeLayer *arcMaskLayer;
@property (nonatomic , strong)UIBarButtonItem *leftBarButtonItem;

@property (weak, nonatomic) IBOutlet UILabel *mileageUnit;
@property (weak, nonatomic) IBOutlet UILabel *totalMileage;
@property (weak, nonatomic) IBOutlet UILabel *batteryLevelTitle;

@property (nonatomic , strong) LXSearchViewController *searchVC;

@property (nonatomic, strong) UIBarButtonItem *leftItem;
@property (nonatomic, strong) UIBarButtonItem *rightItem;


@property (nonatomic , strong)LXFirmwareModel *firmwareModel;

@end

@implementation LXCarHomeViewController

- (LXSearchCarView *)searchView {
    if (!_searchView) {
        _searchView = [[LXSearchCarView alloc] init];
        _searchView.frame = [UIScreen mainScreen].bounds;//self.view.bounds;
        _searchView.delegate = self;
    }
    return _searchView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    [self updateUnits];
    if (self.carModel) {
        [self startGetMessageTimer];
    }
    [self updateLeftBarButton];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self stopTimer];
}

- (void)updateUnits {
    self.speedUnit.text = [IMTUnitHelper speedUnit];
//    self.mileageLB.text = [NSString stringWithFormat:@"%@0.0%@",IMTNewCarLocalizedString(@"car_info_total_mileage"),[IMTUnitHelper mileageUnit]];
    self.thisMileUnitLB.text = [IMTUnitHelper mileageUnit];
    self.toalMileUnitLB.text = [IMTUnitHelper mileageUnit];
    self.maxSpeedUintLB.text = [IMTUnitHelper speedUnit];
    self.averageSpeedUintLB.text = [IMTUnitHelper speedUnit];
    self.temperaturUnitLB.text = [IMTUnitHelper temperatureUnit];

    self.mileageLB.text = @"--";
    self.mileageUnit.text = [IMTUnitHelper mileageUnit];
    self.totalMileage.text = IMTNewCarLocalizedString(@"car_info_total_mileage");
}

- (void)dealloc {
    [self stopTimer];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    UIImageView *topIM = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"top_log"]];
    self.navigationItem.titleView = topIM;
    
    self.backImage.image = [UIImage imageNamed:@"car_speed_out_circle"];
    self.speedValueLB.textColor = [AppTypeTool getThemeColor];
    self.speedUnit.textColor = [AppTypeTool getThemeColor];
    self.speedTitle.text = IMTNewCarLocalizedString(@"fragment_car_status_speed");
    self.maxSpeedTitleLB.text = IMTNewCarLocalizedString(@"fragment_car_status_max_speed");
    self.averageSpeedTitleLB.text = IMTNewCarLocalizedString(@"fragment_car_status_average_speed");
    self.thisMileTitleLB.text = IMTNewCarLocalizedString(@"fragment_car_status_this_mileage");
    self.thisTimeTitleLB.text = IMTNewCarLocalizedString(@"fragment_car_status_riding_time");
    self.temperatureTitleLB.text = IMTNewCarLocalizedString(@"car_info_temp_main_board");
    self.toalMileTitleLB.text = IMTNewCarLocalizedString(@"car_info_total_mileage");
    self.actionTitle_1.text = IMTNewCarLocalizedString(@"fragment_car_status_lock");
    self.actionTitle_2.text = IMTNewCarLocalizedString(@"power_off");
    self.powerOnTimeTitleLB.text = IMTNewCarLocalizedString(@"power_on_time");
    self.bottomBatteryTitleLB.text = IMTNewCarLocalizedString(@"car_info_battery_level");
    
    [[KSBLEManager sharedManager] addStateChangeBlock:^(KSBLEManagerState state) {
        if (self.searchVC) {
            [self.searchVC setBLEManagerStat:state];
        }
        switch (state) {
            case KSBLEManagerStateSubscribed:
                self.carTypeLB.hidden = NO;
                
                [self showSearchVC:NO];
                break;
            default:
                
                [self showSearchVC:YES];
                
                self.carTypeLB.hidden = YES;
                [self updateViewsWithData:NO];
                break;
        }
    } forKey:@""];
    
    
    self.topView.delegate = self;
    self.pageControl.currentPage = 0;
    
    self.arcMaskLayer = [[CAShapeLayer alloc] init];
    self.arcMaskLayer.frame = self.ringMaskView.bounds;

    self.edgesForExtendedLayout = UIRectEdgeNone;   // 修复按钮被tabbar挡住的问题
 
    self.batteryLevelTitle.text = IMTNewCarLocalizedString(@"car_info_battery_level");
    
    
}


- (void)showSearchVC:(BOOL)showSearch {
    if (showSearch) {
        if (!self.searchVC) {
            self.searchVC = [[LXSearchViewController alloc] init];
            
            [self addChildViewController:self.searchVC];
            self.searchVC.view.frame = self.view.bounds;
            [self.view addSubview:self.searchVC.view];
            [self.searchVC didMoveToParentViewController:self];
            
            self.navigationItem.leftBarButtonItem = nil;
            self.navigationItem.rightBarButtonItem = nil;
            __weak __typeof(self)weakSelf = self;
            self.searchVC.searchBlock = ^(CBPeripheral* peripheral) {
                [weakSelf carListViewDidSelectInfo:peripheral];
            };
        }
    } else {
        [self.searchVC willMoveToParentViewController:nil];
        [self.searchVC.view removeFromSuperview];
        [self.searchVC removeFromParentViewController];
        self.searchVC = nil;
        
        self.navigationItem.leftBarButtonItem = self.leftItem;
        self.navigationItem.rightBarButtonItem = self.rightItem;
    }
}

// 连接状态改变后刷新连接按钮
- (void)updateLeftBarButton {
//    if ([KSBLEManager sharedManager].state == KSBLEManagerStateSubscribed) {
//        UIImage *image = [[UIImage imageNamed:@"car_disconnect"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
//        [self.navigationItem.leftBarButtonItem setImage:image];
//        self.navigationItem.leftBarButtonItem.tintColor = kIMTDefaultTitleColor;
//    } else {
////        [self.navigationItem.leftBarButtonItem setImage:[[UIImage imageNamed:@"car_search"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)]];
//        UIImage *image = [[UIImage imageNamed:@"car_search"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
//        [self.navigationItem.leftBarButtonItem setImage:image];
//        self.navigationItem.leftBarButtonItem.tintColor = kIMTDefaultTitleColor;
//    }
    UIImage *image;
    if ([KSBLEManager sharedManager].state == KSBLEManagerStateSubscribed) {
        image = [[UIImage imageNamed:@"car_disconnect"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    } else {
        image = [[UIImage imageNamed:@"car_search"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    }
    [self.leftItem setImage:image];
}

- (UIBarButtonItem *)leftItem {
    if (!_leftItem) {
        _leftItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"car_searach"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:(UIBarButtonItemStylePlain) target:self action:@selector(searchOrDisConnectAction:)];
        _leftItem.tintColor = kIMTDefaultTitleColor;
    }
    return _leftItem;
}

- (UIBarButtonItem *)rightItem {
    if (!_rightItem) {
        _rightItem = [[UIBarButtonItem alloc] initWithImage:[[[UIImage imageNamed:@"ic_settings"] imgWithTintColor:[AppTypeTool getThemeColor]] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:(UIBarButtonItemStylePlain) target:self action:@selector(gotoSettingAction:)];
    }
    return _rightItem;
}


// 搜索/断开操作
- (void)searchOrDisConnectAction:(UIBarButtonItem *)sender {
    if (self.carModel) {
        [self stopTimer];
        [[IMTCANManager sharedInstance] clearMessages];
        [[KSBLEManager sharedManager] disconnect];
        self.carModel = nil;
        
        [self updateLeftBarButton];
    }else {
        [self showProgressHUDWithText:IMTNewCarLocalizedString(@"prompt_loading")];
        [[KSBLEManager sharedManager] startScanWithWithDuration:6 completion:^(NSError *error, NSArray<CBPeripheral *> *peripherals) {
            [self dismissHUD];
            if (error) {
                if (error.code == KSBLEManagerErrorCodeSacnTimeout) {
                    return;
                }
                [self showErrorHUDWithText:error.description];
            }else {
                [self.searchView showdataList:peripherals];
            }
        }];
    }
}

// 跳转车身设置
- (void)gotoSettingAction:(UIBarButtonItem *)sender {
    if (IMTCarSeriesLorin(self.carModel.carType)) {
        LXCarSettingViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"LXCarSettingViewController"];
        vc.carModel = self.carModel;
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        [self showErrorHUDWithText:IMTNewCarLocalizedString(@"prompt_bt_is_not_connected")];
    }
}

#pragma mark ==== 快捷操作
// 操作一 开关灯
- (IBAction)carActionTwo:(UITapGestureRecognizer *)sender {
//      // 开关灯
//    if (self.carModel) {
//        [[IMTCANManager sharedInstance] clearMessages];
//        WS(weakSelf)
//        [self showProgressHUDWithText:nil];
//        __block BOOL isHasShow = NO;
//        if (IMTCarSeriesLorin(self.carModel.carType)) {
//            uint8_t light = (uint8_t)!self.carModel.l9_CarModel.lightSwitch;
//            [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeSetLight) uint8Param:light successBlock:^{
//                [weakSelf showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
//                self.carModel.l9_CarModel.lightSwitch = !self.carModel.l9_CarModel.lightSwitch;
//                isHasShow = YES;
//            } failBlock:^(NSError *error) {
//                [weakSelf showErrorHUDWithText:IMTNewCarLocalizedString(@"setting_failed")];
//                isHasShow = YES;
//            }];
//
//        }
//        if (!isHasShow) {
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [weakSelf dismissHUD];
//            });
//        }
//    }else {
//        [self showErrorHUDWithText:IMTNewCarLocalizedString(@"prompt_bt_is_not_connected")];
//    }
    
    
    // 关机
    [self showProgressHUDWithText:nil];
    [self.carModel.l9_CarModel writeDataWithL9CmdType:(L9_CarModelCmdTypeClooseCar) dataParam:nil successBlock:^{
        [self showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
    } failBlock:^(NSError *error) {
        [self showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
    }];
}

// 操作二 解锁车
- (IBAction)carActionOne:(UITapGestureRecognizer *)sender {
    NSLog(@"=====================操作二");
    if (self.carModel) {
        if (IMTCarSeriesLorin(self.carModel.carType)) {
            if (![LXCustom sharedCustom].needPassword) {
                uint8_t value = !self.carModel.l9_CarModel.lockSwitch;
                [self setCarLockWithValue:value];
            } else {
                [self checkCarIsHasPassword:^(BOOL isHas) {
                    if (isHas) {
                        if (self.carModel.blePassword) {
                            // 使用本地密码验证
                            NSLog(@"==================- 使用本地密码验证");
                            [self checkCarPasswordWithPassword:self.carModel.blePassword block:^(BOOL isok) {
                                if (isok) {
                                    uint8_t value = !self.carModel.l9_CarModel.lockSwitch;
                                    [self setCarLockWithValue:value];
                                }else {
                                    // 弹框提示用户输入密码验证
                                    NSLog(@"==================- 弹框提示用户输入密码验证");
                                    uint8_t value = !self.carModel.l9_CarModel.lockSwitch;
                                    [self showInputPasswordWithType:0 isLock:value];
                                }
                            }];
                        }else {
                            // 弹框提示用户输入密码验证
                            NSLog(@"==================- 弹框提示用户输入密码验证");
                            uint8_t value = !self.carModel.l9_CarModel.lockSwitch;
                            [self showInputPasswordWithType:0 isLock:value];
                        }
                    }else {
                        // 提示输入蓝牙密码设置
                        NSLog(@"==================- 还未设置蓝牙密码");
                        [self showInputPasswordWithType:1 isLock:0];
                    }
                }];
            }
        }
    }else {
        [self showErrorHUDWithText:IMTNewCarLocalizedString(@"prompt_bt_is_not_connected")];
    }
}

//锁车
- (void)setCarLockWithValue:(uint8_t)value {
        
    NSString *mes = nil;
    NSString *successStr = nil;
    NSString *failStr = nil;
    if (value) {
        mes = IMTNewCarLocalizedString(@"prompt_locking");
        successStr = IMTNewCarLocalizedString(@"prompt_lock_success");
        failStr = IMTNewCarLocalizedString(@"prompt_lock_failed");
    }else {
        mes = IMTNewCarLocalizedString(@"prompt_unlocking");
        successStr = IMTNewCarLocalizedString(@"prompt_unlock_success");
        failStr = IMTNewCarLocalizedString(@"prompt_unlock_failed");
    }
    [self showProgressHUDWithText:mes];
    WS(weakSelf)
    [[IMTCANManager sharedInstance] clearMessages];
    __block BOOL isHasShow = NO;
    if (IMTCarSeriesLorin(self.carModel.carType)) {
        [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeLockCar) uint8Param:value successBlock:^{
            self.carModel.l9_CarModel.lockSwitch = value;
            [weakSelf showSuccessHUDWithText:successStr];
            isHasShow = YES;
            NSString *lockImageName = weakSelf.carModel.l9_CarModel.lockSwitch ? @"car_lock" : @"car_unlock";
            weakSelf.actionImage_1.image = [UIImage imageNamed:lockImageName];
            
            NSString *lockName = weakSelf.carModel.l9_CarModel.lockSwitch ? @"fragment_car_status_unlock" : @"fragment_car_status_lock";
            weakSelf.actionTitle_1.text = IMTNewCarLocalizedString(lockName);
        } failBlock:^(NSError *error) {
            [weakSelf showErrorHUDWithText:failStr];
            isHasShow = YES;
        }];
    }
    
    if (!isHasShow) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf dismissHUD];
        });
    }
}


#pragma mark ==== 扫描界面代理
// 取消扫描
- (void)carListViewDidCancel {
    [[KSBLEManager sharedManager] stopScan];
}

// 开始扫描
- (void)carListViewScan {
    [self showProgressHUDWithText:nil];
    [[KSBLEManager sharedManager] startScanWithWithDuration:6 completion:^(NSError *error, NSArray<CBPeripheral *> *peripherals) {
        [self dismissHUD];
        if (error) {
            [self showErrorHUDWithText:error.description];
        }else {
            [self.searchView showdataList:peripherals];
        }
    }];
}

// 已经选择车辆 --- 连接车辆
- (void)carListViewDidSelectInfo:(CBPeripheral *)peripheral {
    [[KSBLEManager sharedManager] connectPeripheral:peripheral success:^(CBPeripheral *peripheral, NSString *macAddress) {
       
        IMCarTypeCode carModelType = IMCarTypeCodeL9;
        
        //MARK: - 判断使用协议类型
        NSLog(@"已经选择车辆名称：%@", peripheral.name);
        if ([BleNameCheck isSupported:peripheral.name]) {
            carModelType = IMCarTypeCodeL9;
        }else {
            carModelType = IMCarTypeCodeOld;
        }
        [IMTCarManager sharedCarManager].carModelType = carModelType;
        CarModel *carModel = [[CarModel alloc] init];
        carModel.bleName = peripheral.name;
        self.carModel = carModel;
        [IMTCarManager sharedCarManager].currentCar = carModel;
        if (carModelType == IMCarTypeCodeL9) {
            L9_CarModel *car = [[L9_CarModel alloc] init];
            car.lx_bleName = peripheral.name;
            self.carModel.l9_CarModel = car;
            // 获取车辆型号
            [car getProductMessageCompleBlock:^(NSError *error, NSData *responseData) {
                if (IMTCarSeriesLorin(car.LX_CarType)) {
                    
                    // E20不支持设置功能
                    if (IMTCarSeriesE20(car.LX_CarType)) {
                        [IMTUnitHelper setUseMetricUnit:true];
                        self.navigationItem.rightBarButtonItem = nil;
                        [self.actionView_1 setHidden:YES];
                        [self.actionView_2 setHidden:YES];
                    } else {
                        [self.actionView_1 setHidden:NO];
                        [self.actionView_2 setHidden:NO];
                    }
                    
//                    [self showSuccessHUDWithText:IMTNewCarLocalizedString(@"connected_successfully")];
                    self.carTypeLB.text = car.lx_bleName;
                    self.carModel.carType = car.LX_CarType;
                    // 获取sn
                    [self.carModel.l9_CarModel getCarSNWithCompleBlock:^(NSError *error, NSData *responseData) {
                        NSLog(@"获取车辆sn的结果 ================= 🌞🌞  %@ == %@",error,responseData);
                        self.carModel.sn = car.lx_sn;
                        // 获取本地密码
                        [self.carModel.l9_CarModel loadLocalCarBlePassword];
                        
                        [self getCarActivationMessage];
                    }];
                    [self.carModel.l9_CarModel getCarMaxSpeedWithCompleBlock:^(NSError *error, NSData *responseData) {
                        NSLog(@"获取车辆最大设计限速的结果 ================= 🌞  %@ == %@",error,responseData);
                    }];
                    [self updateLeftBarButton];
                }else {
                    [self showErrorHUDWithText:IMTNewCarLocalizedString(@"connection_failed")];
                }
            }];
        }else {
            [self showErrorHUDWithText:IMTNewCarLocalizedString(@"connection_failed")];
        }
    } failure:^(NSError *error) {
        [self showErrorHUDWithText:IMTNewCarLocalizedString(@"connection_failed")];
    }];
}

// 获取车辆激活信息
- (void)getCarActivationMessage {
    if (IMTCarSeriesLorin(self.carModel.carType)) {
        [self.carModel.l9_CarModel getCarDeviceActivationStatuSsuccessBlock:^{
            [self startGetMessageTimer];
            
            // 读取当前固件版本号
            [self.carModel.l9_CarModel getCarVersionSuccessBlock:^{
                [self checkCarIsNeedUpdate];
            } failBlock:^(NSError *error) {
            }];
            
        } failBlock:^(NSError *error) {
            LXActivationViewController *vc = [[LXActivationViewController alloc] initWithNibName:@"LXActivationViewController" bundle:nil];
            vc.carModel = self.carModel.l9_CarModel;
            [self.navigationController pushViewController:vc animated:YES];
//            checkCarIsNeedUpdate
        }];
    }
}

- (void)checkCarIsNeedUpdate {
    
    if (IMTCarSeriesE20(self.carModel.carType)) {
        return;
    }
    
    // 请求服务器固件版本
    NSDictionary *parame = @{@"sn":self.carModel.l9_CarModel.lx_sn,@"carType":self.carModel.l9_CarModel.LX_CarType,@"version":self.carModel.l9_CarModel.versionData,@"upgradeCode":@""};
    // 请求当前固件版本
    [[IMTHTTPSessionManager sharedInstance] ks_POST:@"checkOemFwUpgrade" parameters:parame success:^(NSURLSessionDataTask *task, id responseObject) {
        if (responseObject) {
            [self.firmwareModel loadDataFromResponseData:responseObject];
            if (self.firmwareModel.fileUrl) {
//                UIAlertController *vc = [UIAlertController alertControllerWithTitle:IMTNewCarLocalizedString(@"car_feature_fw_upgrade") message:self.firmwareModel.descriptionText preferredStyle:(UIAlertControllerStyleAlert)];
//                UIAlertAction *cancle = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"dialog_cancel") style:(UIAlertActionStyleCancel) handler:nil];
//                UIAlertAction *sure = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"dialog_ok") style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                    NewFirmwareUpdateViewController *firmwareUpate = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"NewFirmwareUpdateViewController"];
                    firmwareUpate.carModel = self.carModel;
                    if (self.firmwareModel.level > 0) {
                        firmwareUpate.firmwareModel = self.firmwareModel;
                    }
                    
                    [self.navigationController pushViewController:firmwareUpate animated:YES];
//                }];
//                [vc addAction:cancle];
//                [vc addAction:sure];
//                [self presentViewController:vc animated:YES completion:nil];
                
                
//                if (self.firmwareModel.level > 0) {
//                    [self.carModel.l9_CarModel setCarNeedUploadWithRank:self.firmwareModel.level lowest:self.firmwareModel.minVersion highest:self.firmwareModel.maxVersion successBlock:^{
//                        NSLog(@"写入成功");
//                    } failBlock:^(NSError *error) {
//                        NSLog(@"写入失败");
//                    }];
//                }
                
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"err = %@", error);
        [self showErrorHUDWithText:nil];
    }];
    
}

- (LXFirmwareModel *)firmwareModel {
    if (!_firmwareModel) {
        _firmwareModel = [[LXFirmwareModel alloc] init];
    }
    return _firmwareModel;
}



// 获取车辆信息数据
- (void)startGetMessageTimer {
    if (self.timer.isValid) {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(getCarMessage:) userInfo:nil repeats:YES];
}

- (void)getCarMessage:(NSTimer *)timer {
    if (IMTCarSeriesLorin(self.carModel.carType)) {
        [self.carModel.l9_CarModel getDataWithCmdType:L9_CarModelCmdTypeRealTimeComplex isRepeat:NO compleBlock:^(NSError *error, NSData *responseData) {
            NSLog(@"获取实时数据 ======= %@ == %@",error,[self convertDataToHexStr:responseData]);
            self.carModel.speed = self.carModel.l9_CarModel.currentSpeed;
            self.carModel.leftMiles = self.carModel.l9_CarModel.thisTime_mileage;
            self.carModel.battery = self.carModel.l9_CarModel.battery_percent;

            [self updateViewsWithData:YES];
        }];
        int8_t cmd = IMTCarSeriesE20(self.carModel.carType) ? L9_CarModelCmdTypeBrakeForce : L9_CarModelCmdTypeSingleData;
        if (IMTCarSeriesE20(self.carModel.carType)) {
            // 单次统计数据
            uint16_t param = (1<<8)|0;
            [self.carModel.l9_CarModel getDataWithCmdType: cmd data16Param: param isRepeat:NO compleBlock:^(NSError *error, NSData *responseData) {
                self.carModel.averageSpeed = self.carModel.l9_CarModel.averageSpeed;
                self.carModel.rideTime = self.carModel.l9_CarModel.thisTime_rideTime;
                self.carModel.powerOnTime = self.carModel.l9_CarModel.power_on_time;

                [self updateViewsWithData:YES];
            }];
            [self.carModel.l9_CarModel getDataWithCmdType: L9_CarModelCmdTypeSetMaxSpeed isRepeat:NO compleBlock:^(NSError *error, NSData *responseData) {
                self.carModel.mileage = self.carModel.l9_CarModel.total_mileage;

                [self updateViewsWithData:YES];
            }];
        } else {
            [self.carModel.l9_CarModel getDataWithCmdType:cmd isRepeat:NO compleBlock:^(NSError *error, NSData *responseData) {
                self.carModel.currentMaxSpeed = self.carModel.l9_CarModel.currentMaxSpeed;
                self.carModel.averageSpeed = self.carModel.l9_CarModel.averageSpeed;
                self.carModel.rideTime = self.carModel.l9_CarModel.thisTime_rideTime;
                
                self.carModel.powerOnTime = self.carModel.l9_CarModel.power_on_time;
                [self updateViewsWithData:YES];
            }];
        }
    }
}

- (void)updateViewsWithData:(BOOL)isConnect {
    
    // 速度
    self.speedValueLB.text = isConnect ? [NSString stringWithFormat:@"%.1f",[IMTUnitHelper speedForValue:self.carModel.speed]] : @"--";
    [self showSpeedAnimation:self.carModel.speed/30];
    // 总里程
//    self.mileageLB.text = [NSString stringWithFormat:@"%@:%.0f%@",IMTNewCarLocalizedString(@"car_info_total_mileage"),isConnect ? [IMTUnitHelper mileageForValue:self.carModel.mileage] : 0.0,[IMTUnitHelper mileageUnit]];
    
    self.mileageLB.text = isConnect ? [NSString stringWithFormat:@"%.1f",[IMTUnitHelper mileageForValue:self.carModel.mileage]] : @"--";
    self.mileageUnit.text = [IMTUnitHelper mileageUnit];
    self.totalMileage.text = IMTNewCarLocalizedString(@"car_info_total_mileage");
    
    // 电量
    self.batteryLB.text = [NSString stringWithFormat:@"%.0f%%",isConnect ? self.carModel.battery : 0];
    self.batteryValueConstraint.constant = isConnect ? 20*self.carModel.battery/100 : 0;
    self.batteryViewConstraint.constant = isConnect ? kIMTScreenWidth * 0.7 *self.carModel.battery/100 : 0;
    self.battreyView.backgroundColor = self.carModel.battery > 20 ? [AppTypeTool getThemeColor] : IMTColor(163, 53, 52);
    
    // 九宫格数据
    self.maxSpeedValueLB.text = isConnect ? [NSString stringWithFormat:@"%.1f", [IMTUnitHelper speedForValue:self.carModel.currentMaxSpeed]] : @"--";
    self.averageSpeedLB.text = isConnect ? [NSString stringWithFormat:@"%.1f", [IMTUnitHelper speedForValue:self.carModel.averageSpeed]] : @"--";
    self.thisTimeValueLB.text = isConnect ? [NSString stringWithFormat:@"%0.1f", self.carModel.rideTime] : @"--";
    self.thisMileValueLB.text = isConnect ? [NSString stringWithFormat:@"%.1f", [IMTUnitHelper mileageForValue:self.carModel.leftMiles]] : @"--";
    self.temperatureValueLB.text = isConnect ? [NSString stringWithFormat:@"%.1f", [IMTUnitHelper temperatureForValue:self.carModel.temperature]] : @"--";
    self.toalMileValueLB.text = isConnect ? [NSString stringWithFormat:@"%.1f", [IMTUnitHelper mileageForValue:self.carModel.mileage]] : @"--";
    
    
    self.powerOnTimeValueLB.text = isConnect ? [NSString stringWithFormat:@"%0.1f", self.carModel.powerOnTime] : @"--";
    self.bottomBatteryValueLB.text = isConnect ? [NSString stringWithFormat:@"%.0f",isConnect ? self.carModel.battery : 0] : @"--";
    
    
    // 快捷操作
    NSString *lockImageName = self.carModel.isLocked ? @"car_lock" : @"car_unlock";
    self.actionImage_1.image = [UIImage imageNamed:lockImageName];
    
    NSString *lockName = self.carModel.isLocked ? @"fragment_car_status_unlock" : @"fragment_car_status_lock";
    self.actionTitle_1.text = IMTNewCarLocalizedString(lockName);

}

#pragma mark ======== 速度动画
- (void)showSpeedAnimation:(CGFloat)percent {
    self.desAngle = -M_PI*(5.0/4.0) + M_PI*percent*6.0/4.0;
    self.count = 0;
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateArcLayer:)];
    [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:(NSRunLoopCommonModes)];

}

- (void)updateArcLayer:(CADisplayLink *)displayLink {
    if (self.count > 30) {
        [displayLink invalidate];
        self.lastAngle = self.desAngle;
        return;
    }
    CGFloat angle = self.lastAngle + self.count*(self.desAngle - self.lastAngle)/30.0;
    self.count += 1;
    CGPoint center = CGPointMake(CGRectGetMidX(self.ringMaskView.frame), CGRectGetMidY(self.ringMaskView.frame));
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:self.ringMaskView.bounds.size.width/2 startAngle:angle endAngle:M_PI/4.0 clockwise:YES];
    [path addLineToPoint:center];
    [path closePath];
    [CATransaction setDisableActions:YES];
    self.arcMaskLayer.path = path.CGPath;
    [CATransaction setDisableActions:NO];
    self.arrowView.transform = CGAffineTransformMakeRotation(angle + M_PI*(2.0/4.0));
}

- (void)stopTimer {
    if (self.timer.isValid) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

#pragma mark ====  UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    BOOL scrollToScrollStop = !scrollView.tracking && !scrollView.dragging && !scrollView.decelerating;
        if (scrollToScrollStop) {
            [self scrollViewDidEndScroll:scrollView];
        }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        BOOL dragToDragStop = scrollView.tracking && !scrollView.dragging && !scrollView.decelerating;
        if (dragToDragStop) {
            [self scrollViewDidEndScroll:scrollView];
        }
    }
}

- (void)scrollViewDidEndScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.x == 0) {
        self.pageControl.currentPage = 0;
    }else {
        self.pageControl.currentPage = 1;
    }
}

#pragma mark ======= 锁车验证
// 判断车辆是否存在密码
- (void)checkCarIsHasPassword:(void(^)(BOOL))block {
    
    if (self.carModel.blePassword) { // 本地存在密码
        if (block) {
            block(YES);
        }
    }else { // 本地不存在密码
        [[IMTCANManager sharedInstance] clearMessages];
        [self.carModel.l9_CarModel checkBlePasswordWithPassword:nil successBlock:^{
            NSLog(@" ========== 车辆不存在密码");
            if (block) {
                block(NO);
            }
        } failBlock:^(NSError *error) {
            NSLog(@"========== 车辆存在密码");
            if (block) {
                block(YES);
            }
        }];
    }
}

// 验证密码
- (void)checkCarPasswordWithPassword:(NSString *)password block:(void(^)(BOOL))block{
    [[IMTCANManager sharedInstance] clearMessages];
    [self.carModel.l9_CarModel checkBlePasswordWithPassword:[IMFunction strToAscll:password] successBlock:^{
        NSLog(@" ========== 车辆密码验证通过");
        self.carModel.l9_CarModel.blePassword = password;
        [self.carModel.l9_CarModel saveCarBlePassword];
        if (block) {
            block(YES);
        }
    } failBlock:^(NSError *error) {
        NSLog(@"========== 车辆密码不通过");
        if (block) {
            block(NO);
        }
    }];
}

// 安全连接
- (void)safeConnect:(NSString *)password {
    WS(weakSelf)
    [[IMTCANManager sharedInstance] clearMessages];
    [self.carModel.l9_CarModel getSafeChannelWithCompleBlock:^(NSError *error, NSData *responseData) {
        if (error == nil && weakSelf.carModel.l9_CarModel.randomCode) {
            [weakSelf.carModel.l9_CarModel setSafePasswordWithPassword:weakSelf.carModel.l9_CarModel.randomCode successBlock:^{
                [weakSelf writePasswordToCar:password];
            } failBlock:^(NSError *error) {
                [weakSelf showErrorHUDWithText:IMTNewCarLocalizedString(@"setting_failed")];
                return;
            }];
        }else {
            [weakSelf showErrorHUDWithText:IMTNewCarLocalizedString(@"setting_failed")];
            return;
        }
    }];
}

// 写入密码
- (void)writePasswordToCar:(NSString *)password {
    NSData *param = [IMFunction strToAscll:password];
    [[IMTCANManager sharedInstance] clearMessages];
    [self.carModel.l9_CarModel writeBlePasswordWithPassword:param successBlock:^{
        self.carModel.blePassword = password;
        [self.carModel.l9_CarModel saveCarBlePassword];
        [self showSuccessHUDWithText:IMTNewCarLocalizedString(@"prompt_change_bt_pwd_successfully")];
        [self.navigationController popViewControllerAnimated:YES];
    } failBlock:^(NSError *error) {
        [self showErrorHUDWithText:IMTNewCarLocalizedString(@"prompt_change_bt_pwd_failed")];
    }];
}

- (void)showInputPasswordWithType:(NSInteger)type isLock:(uint8_t)lockValue {
    NSString * title = @"";
    if (type == 0) {
        title = IMTNewCarLocalizedString(@"dialog_input_pwd_hint");
    }
    if (type == 1) {
        title = IMTNewCarLocalizedString(@"prompt_goto_set_pwd");
    }

    UIAlertController *ac = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    [ac addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = IMTNewCarLocalizedString(@"dialog_input_pwd_hint");
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.secureTextEntry = YES;
    }];
    if (type == 1) {
        [ac addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = IMTNewCarLocalizedString(@"activity_change_bt_pwd_hint_confirm_new_pwd");
            textField.keyboardType = UIKeyboardTypeNumberPad;
            textField.secureTextEntry = YES;
        }];
    }
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"dialog_ok") style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UITextField *psField = ac.textFields[0];
        if (type == 0) {
            [self checkCarPasswordWithPassword:psField.text block:^(BOOL isok) {
                if (isok) {
                    [self showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
                    // 解锁车辆
                    [self setCarLockWithValue:lockValue];
                }else {
                    [self showErrorHUDWithText:IMTNewCarLocalizedString(@"setting_failed")];
                }
            }];
        }
        if (type == 1) {
            UITextField *surepsField = ac.textFields[1];
            if ([psField.text isEqualToString:surepsField.text]) {
                [self safeConnect:psField.text];
            }else {
                [self showErrorHUDWithText:IMTNewCarLocalizedString(@"prompt_change_bt_pwd_confirm_pwd_not_match")];
            }
        }
    }];
    UIAlertAction *Cancel = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"dialog_cancel") style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
    }];
    [ac addAction:confirm];
    [ac addAction:Cancel];
    [self presentViewController:ac animated:YES completion:nil];
}


- (NSString *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];

    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];

    return string;
}


@end
